const fs = require("fs");
const path = require("path");
/**
 * 下划线转驼峰方法
 */
function underlineToHump(str) {
  var a = str.split("_");
  var result = a[0];
  for (var i = 1; i < a.length; i++) {
    result = result + a[i].slice(0, 1).toUpperCase() + a[i].slice(1);
  }
  return result;
}

/**
 * 生成contract文件
 * @param {*} config
 */
function buildContract(config) {
  let str = `module.exports = {\r\n`;
  str += `  ${config.module.charAt(0).toUpperCase() + config.module.slice(1)}${
    config.moduleName.charAt(0).toUpperCase() + config.moduleName.slice(1)
  }List: {
    code: { type: "number", example: 200 },
    msg: { type: "string", example: "操作成功" },     
    data: { type: "array", itemType: "${
      config.module.charAt(0).toUpperCase() + config.module.slice(1)
    }${
    config.moduleName.charAt(0).toUpperCase() + config.moduleName.slice(1)
  }_item" },
  },
  ${config.module.charAt(0).toUpperCase() + config.module.slice(1)}${
    config.moduleName.charAt(0).toUpperCase() + config.moduleName.slice(1)
  }_item: {\r\n`;
  config.data.forEach((item) => {
    str += `    ${underlineToHump(item.columnName)}: { type: "${
      item.javaType
    }", description: "${item.columnComment}" },\r\n`;
  });
  str += `  },\r\n`;
  str += `  ${config.module.charAt(0).toUpperCase() + config.module.slice(1)}${
    config.moduleName.charAt(0).toUpperCase() + config.moduleName.slice(1)
  }: {
    code: { type: "number", example: 200 },
    msg: { type: "string", example: "操作成功" },
    data: {
      type: "object",
      properties: {\r\n`;
  config.data.forEach((item) => {
    str += `        ${underlineToHump(item.columnName)}: { type: "${
      item.javaType
    }", description: "${item.columnComment}" },\r\n`;
  });
  str += `      },
    },
  },
}`;

  // 生成 contract 文件
  const contractFile = path.join(
    __dirname,
    "..",
    "..",
    "..",
    "autoModule",
    "service",
    "app",
    "contract",
    config.module,
    `${config.moduleName}.js`
  );

  if (!fs.existsSync(contractFile)) {
    fs.writeFileSync(contractFile, str);
  }
  console.log(`生成 ${config.moduleName} 模块的contract文件成功！`);
}

module.exports = {
  buildContract,
};
